import React,{Component} from 'react'
import Pages from '../Pages'
import '../../style/admin_less/point.less';
import {Urls} from '../../config/urls'
import * as pub from '../../config/public'
import { Spin,message,Button} from 'antd';
import Layer from '../Layer'
import $ from 'jquery'
import Dropzone from 'react-dropzone'
import sfetch from 'sfetch' 
import * as fetch from '../../config/fetch';
class AddGood extends Component {
	constructor(props) {
		super(props)
		this.state = {
			visible: false,
			cover_image:[],
			categoriesList:[],
			is_choose_image:false,
			delflag:this.props.delflag?this.props.delflag:'A',
			shopId:this.props.shopId?this.props.shopId:'',
			shopName:this.props.shopName?this.props.shopName:'',
			exchangeIntegral:this.props.Intergral?this.props.Intergral:'',
			stock:this.props.stock?this.props.stock:'',
			categories:this.props.categories?this.props.categories:'',
			commodityType:this.props.commodityType?this.props.commodityType:'',
			showDHM:false,
			redeemCode:this.props.redeemCode?this.props.redeemCode:''
		}
	}
	componentWillMount(){
		this.getType();
	}
	getType(){
		let data = pub.behavior({
			pid: 0
		}, 'categoriesList', 'button')
		$.ajax({
			url: Urls.CATEGORIESLIST,
			data: data,
			success: (data) => {
				if(data.result === 'RC100'){
					this.setState({
						categoriesList: data.categoriesList ? data.categoriesList : [],
					},()=>{
						let categoriesList1=[];
						for(let x of this.state.categoriesList){
							if(x.code!=='171207154510'){
								categoriesList1.push(x);
							}
						}
						this.setState({
							categoriesList:categoriesList1
						})
						})
				}else{
					message.error(data.errMsg,3)
				}
			}
		})
	}
	componentWillReceiveProps(nextProps) {
		this.getType();
		this.setState({
			LayerTitle: nextProps.LayerTitle,
			visible: nextProps.modalshow,
			shopId: nextProps.shopId ? nextProps.shopId : '',
			delflag: nextProps.delflag,
			shopName: nextProps.shopName,
			exchangeIntegral: nextProps.exchangeIntegral,
			stock: nextProps.stock,
			shopCover: nextProps.shopCover,
			commodityType: nextProps.commodityType,
			redeemCode:nextProps.redeemCode
		},()=>{
			 if(this.state.commodityType==='171207154510'){
					$(".operationType").prop("checked",true);
					this.setState({
				        showDHM:true,
						redeemCode:this.state.redeemCode
					})
			 }else{
				 this.setState({
				        showDHM:false,
						redeemCode:this.state.redeemCode
					})
			 }
		});
	}
	
	
	showModal = () => {
		this.setState({
			LayerTitle:"新增商品",
			visible: true,
			shopName:'',
    		stock:'',
    		exchangeIntegral:'',
    		cover_image:[],
    		shopCover:'',
    		shopId:'',
			redeemCode:'',
			showDHM:false
		});
		let data = pub.behavior({
			pid:0
			},'categoriesList','button')
		$.ajax({
			url:Urls.CATEGORIESLIST,
			data:data,
			success:(data)=>{
				this.setState({
					categoriesList:data.categoriesList?data.categoriesList:[]
				},()=>{
					let categoriesList1=[];
					for(let x of this.state.categoriesList){
						if(x.code!=='171207154510'){
							categoriesList1.push(x);
						}
					}
					this.setState({
						categoriesList:categoriesList1
					})
				})
			}
		})
	}
	hideMdoal = (e) => {
			this.props.modalhidden()
			this.setState({
				visible: false,
				categoriesList:[],
				is_choose_image:false,
				shopName:'',
    			stock:'',
				file:'',
    			exchangeIntegral:'',
    			cover_image:[],
    			shopCover:'',
				redeemCode:'',
				commodityType:'',
				shopId:'',
				showDHM:false,
				categories:'',
			});
	}
	chooseImage(accepted, rejected){
		
		this.setState({
			cover_image:accepted[0],
			is_choose_image:true,
			shopCover:''
		})
	}
	shopName=(event)=>{
		if(event.target.value.length<=20){
           this.setState({shopName:event.target.value})
		}else{
			event.target.value="";
			message.warning('商品名称不能超过20字！')
		}
	}
	commodityType=(event)=>{
		this.setState({commodityType:event.target.value})
	}
	stock=()=>{
		this.setState({stock:this.refs.stock.value.replace(/[^\d]/g,'')})
	}
	exchangeIntegral=(event)=>{
		if(event.target.value.length<=20){
            this.setState({exchangeIntegral:event.target.value.replace(/[^\d]/g,'')})
		}else{
			event.target.value=""
			message.warning('兑换积分不能超过20位！')
		}
	}
	onSubmit(e){
		e.preventDefault();
		let formData = new FormData();
		    if(this.state.showDHM===true){
				formData.append('redeemCode',this.state.redeemCode);
				formData.append('commodityType','171207154510');
				//formData.append('stock',null);
			}else{
				formData.append('commodityType',this.refs.categories.value);
				formData.append('stock',this.state.stock);
			}
			formData.append('delflag',this.state.delflag?this.state.delflag:'A');
			formData.append('shopName',this.state.shopName);
			formData.append('exchangeIntegral',this.state.exchangeIntegral);		
			formData.append('shopId',this.state.shopId);
			formData.append('shopCover',this.state.shopCover);
			  if(this.state.shopCover===''){
		        formData.append('file',this.state.cover_image);
		     }else{
		        formData.append('file',this.state.shopCover);
		     }
		let url= pub.url_format(Urls.INTEGRALMALLMANAGEMENT,'iudGoods','button')
		sfetch.post({
      		url: url,
     		 body: formData,
      		dataType: 'formdata'
    }).then((data) => {
    		if(data.json.result ==='RC100'){
    			
	    		this.props.show()
	    		this.setState({
					visible: false,
					categoriesList:[],
					is_choose_image:false,
	    			shopName:'',
	    			stock:'',
	    			exchangeIntegral:'',
	    			file:'',
	    			cover_image:[],
					shopId:'',
					commodityType:'',
					showDHM:false,
					redeemCode:'',
					shopCover:'',
					categories:'',

	    		})
    		}
     		 else {
	       	   message.error(data.json.errMsg,3);
	      	}
	    });
	    this.setState({
			modalshow: false,
		});
	}
	numberInputs=(e)=>{
		let value=e.target.value;
		e.target.value=value.replace(/[@#%&{}?/><[()（）【】{}《》'“‘”’]+/g,'');
	}
	checkType(){
		if(this.state.showDHM===true){
             this.setState({
				showDHM:false
			},()=>{
                $(".operationType").prop("checked",false);
			})
		}else{
			this.setState({
				showDHM:true
			},()=>{
				$(".operationType").prop("checked",true);
			})
		}
	}
	redeemCode=(e)=>{
        this.setState({ 
			redeemCode:e.target.value.replace(/[^\w\.\/]/ig,'')
		},()=>{
			if(this.state.redeemCode.length>6){
				message.warning('兑换码不能超过6位！')
				this.setState({
					redeemCode:''
				})
			}
		})
	}
	render(){
		return(
	    <div>
			<Layer
				title = {this.state.LayerTitle}
				show={this.state.visible}
				hide={(e)=>this.hideMdoal(e)}
				width="750px"
				height="450px"
			>
				<form className="layui-layer-content" onSubmit={(e)=>this.onSubmit(e)}>
					<div className="row">
					
					
						<div className="pop-box-1">
							<div className="good-add clearFix">
							{   this.state.showDHM?<img src={require('../../style/images/ewm.jpg')} alt='封面图片' />:
								(this.state.shopCover ===''?
								<img src={this.state.cover_image.preview} alt='封面图片' />
								:<img src={pub.getFile(this.state.shopCover)} alt='封面图片' />)
							}
								<ul className="good-info">
									<li>
										<label className='label-book2'>
											{
												this.state.LayerTitle==="编辑商品"?
												<input onClick={() => this.checkType()} className="operationType" type="radio" disabled="true" name='operationType'/>:
												<input onClick={() => this.checkType()} className="operationType" type="radio" name='operationType'/>
											}
										课程兑换码</label>
									  {
										  this.state.showDHM?
                                           <input type="text" required="required" value={this.state.redeemCode}  onChange={this.redeemCode.bind()}/>:null
									  }
									</li>
									<li><label><span>*</span>商品名称：</label><input type="text" required="required" value={this.state.shopName}  onChange={this.shopName.bind()}/></li>
									<li><label><span>*</span>商品类型：</label>
									{
                                         this.state.showDHM?
										 <input type="text" value='兑换码'  disabled="true"/>:
                                         <select required="required"  value={this.state.commodityType} onChange={this.commodityType.bind()} ref="categories" id="mySelect">
											{this.state.categoriesList.map((item,index)=>{
												return(
													<option key={index} value={item.code}>{item.name}</option>
												)
											})}
									     </select>
									}
									</li>
									{
										this.state.showDHM?null:
										<li><label><span>*</span>商品库存：</label><input type="text" required="required" maxLength="6" value={this.state.stock} onChange={this.stock.bind()} ref='stock'/></li>
									}
									<li><label><span>*</span>兑换积分：</label><input type="text" value={this.state.exchangeIntegral} required="required" onChange={this.exchangeIntegral.bind()} ref='Integral' /></li>
								</ul>
								{
									this.state.showDHM?null:
									<Dropzone
									// maxSize= {31457280}
									multiple={false}
									onDrop={this.chooseImage.bind(this)}
									className = 'choose-image'
									accept="image/jpeg, image/png"
								    >
									<label className="file" >上传封面</label>
	
								    </Dropzone>
								}
	
							</div>
						</div>
						<div className="pop-btn">
							<a className="btn btn-grey layui-layer-close" onClick={(e)=>this.hideMdoal(e)}>取消</a>
							<button type='submit' className="btn add-book" >确定</button>
						</div>
					</div>
				</form>
			</Layer>
           <a className="btn btn-blue add-new"  onClick={()=>this.showModal()}>新增</a>

		</div>

			)
	}
}

class PointShopManage extends Component {
	constructor(args) {
		super()
		this.state = {
			IntegralShopList:[],
			totalPage:'',
			pageno:1,
			showLayer:false,
			deletePSId:'',
			checkState:''
		}		
	}
	show(){
		let _this = this
		this.setState({loading:true})
		let data = pub.behavior({
				pageno:this.state.pageno,
				delflag:this.state
			},'selectGoods','menu')
		$.ajax({
			url:Urls.INTEGRALMALLLIST,
			data:data,
			success:function(data){
				_this.setState({totalPage:data.totalPage})
				_this.setState({IntegralShopList:data.IntegralShopList?data.IntegralShopList:[]})
				_this.setState({loading:false})
				
			},
			error:function(data){
				message.error('请求失败',3);
			}
		})
		this.setState({modalshow:false})
	}
	componentWillMount(){
		this.show()
	}
	edit(item,index){
		let str0 = item.shopId
		let formData = new FormData();
			formData.append('shopId',str0);
		let url= pub.url_format(Urls.SELECTGOODS,'selectGoods','button')
		sfetch.post({
      		url: url,
     		body: formData,
      		dataType: 'formdata'
    	}).then((data) => {
    		/*console.log(data.json.integralShop)
    		console.log(data)*/
    		this.setState({
    			LayerTitle:"编辑商品",
    			modalshow:true,
    			shopId:data.json.integralShop.shopId,
    			shopName:data.json.integralShop.shopName,
    			exchangeIntegral:data.json.integralShop.exchangeIntegral,
    			stock:data.json.integralShop.stock,
    			shopCover:data.json.integralShop.shopCover,
    			commodityType:data.json.integralShop.commodityType,
				redeemCode:data.json.integralShop.redeemCode,
    			delflag:'U',
    			
    		})
     		 if (data.ok) {
	        	/*console.log(data.json)*/
	     	 } else {
	       	 /*console.log(data)*/
	       		message.error(data.errMsg,3);
	      	}
	    });
		
		
	}
	jump(page){
		let _this = this
		this.setState({pageno:page})
		let data = pub.behavior({
				pageno:page
			},'selectGoods','menu')
		$.ajax({
			url:Urls.INTEGRALMALLLIST,
			data:data,
			success:function(data){
				_this.setState({modalshow:false})
				_this.setState({totalPage:data.totalPage})
				_this.setState({IntegralShopList:data.IntegralShopList?data.IntegralShopList:[]})	
			},
			error:function(data){
				message.error('请求失败',3);
			}
		})
	}
	del(item,index) {
		item.liveStats = "D"
		let _this =this
		this.setState({shopId:item.shopId,deflag:item.delflag})
		let data = pub.behavior({
				shopId:item.shopId,
				delflag:'D'
			},'iudGoods','button')
		$.ajax({
			type:"POST",
			url:Urls.INTEGRALMALLMANAGEMENT,
			data:data,
			success:function(data){
				let odata = pub.behavior({
						pageno:_this.state.pageno
					},'selectGoods','menu')
					$.ajax({
						url:Urls.INTEGRALMALLLIST,
						data:odata,
						success:function(data){
							_this.setState({IntegralShopList:data.IntegralShopList?data.IntegralShopList:[]})
						},
						error:function(data){
							message.error('请求失败',3);
						}
					})
			}
		})
	}
	searchinglist(){
		let str =  this.refs.searchModel.value
		let _this =this
		let data = pub.behavior({
				shopName:str
			},'selectLiveInfoList','button')
		$.ajax({
			url:Urls.INTEGRALMALLLIST,
			data:data,
			success:function(data){
				_this.setState({IntegralShopList:data.IntegralShopList?data.IntegralShopList:[]})
				_this.setState({totalPage:data.totalPage?data.totalPage:0})
			},
			error:function(data){
				message.error('请求失败',3);
			}
		})
	}
	modalhidden(){
		this.setState({
			modalshow:false
		})
	}
	//搜索框去特殊符号
	numberInputr=(e)=>{
		let value=e.target.value;
		e.target.value=value.replace(/[@#%&{}?/><[()（）【】{}《》'“‘”’]+/g,'');
	}
	deletePSId(id){
		this.setState({
			showLayer:true,
			deletePSId:id
		})
	}
	deletePShideModel(){
		this.setState({
			showLayer:false
		})
	}
	//上架+删除
	uporPSDelete(shopId,type) {
		pub.loading(this, true);
		let body={}
		if(type==='A'){
            body={shopId:shopId,delflag:type}
		}else{
			body={shopId:this.state.deletePSId,delflag:type}
		}
		fetch.uporPSDelete(body).then((data) => {
			if (data.result === 'RC100') {
				this.show();
				this.setState({
					deletePSId:'',
					showLayer:false
				})
			} else {
				message.error(data.errMsg, 3);
			}
			pub.loading(this, false);
		}, (res) => {
			pub.loading(this, false);
			pub.reject(res);
		})
	}
	render() {
		return (
			<div className="container pointShopManage">
			   	<div className="common-title">积分商城
					<div className="filter-search floatR">
						<input type="text" placeholder="搜索" ref='searchModel'  onKeyUp={this.numberInputr}/>
						<a className="btn search-btn" onClick={()=>this.searchinglist()}><i className="icon-search"></i></a>
					</div>
				</div>

				<div className="row select-filter">
					<div className="floatL">
					<select value={this.state.checkState} onChange={(e)=>{this.setState({checkState:e.target.value},()=>{this.show();})}}>
						<option value=''>全部状态</option>
						<option value='1'>上架</option>
						<option value='2'>下架</option>
					</select>
					</div>
					<AddGood modalshow={this.state.modalshow} modalhidden={this.modalhidden.bind(this)} show={this.show.bind(this)} shopId={this.state.shopId} shopName={this.state.shopName} exchangeIntegral={this.state.exchangeIntegral} stock={this.state.stock} shopCover={this.state.shopCover} delflag={this.state.delflag} commodityType={this.state.commodityType} LayerTitle={this.state.LayerTitle} redeemCode={this.state.redeemCode}/>
				</div>
				<div className="row pad-t-20">
					<div className="goods-list">
					<Spin spinning={this.state.loading} tip="加载列表中...">
					<ul className="clearFix">
					{this.state.IntegralShopList.map((item,index)=>{
						return(
							<li key={index}>
								{
									item.shopCover===''?
									<img src={require('../../style/images/ewm.jpg')} alt="goods"/>:<img src={pub.getFile(item.shopCover)} alt="goods"/>
								}
								<div className="good-details">
									<p className="name">{item.shopName}</p>
									<p className="integral">兑换积分：<span>{item.exchangeIntegral}</span></p>
									<p className="number">库存量：&emsp;<span>{item.stock}</span></p>
									<div className="good-btn">
										{(JSON.parse(localStorage.getItem('user')).manageCom).length===1&&item.delflag==='A'||item.delflag==='U'?<a onClick={()=>this.edit(item,index)} >编辑</a>:null}
										{(JSON.parse(localStorage.getItem('user')).manageCom).length===1&&item.delflag==='A'||item.delflag==='U'?<a className="red" onClick={()=>this.del(item,index)}>下架</a>:null}
										{(JSON.parse(localStorage.getItem('user')).manageCom).length===1&&item.delflag==='D'?<a className="red" onClick={()=>this.uporPSDelete(item.shopId,'A')}>上架</a>:null}
										{(JSON.parse(localStorage.getItem('user')).manageCom).length===1?<a className="red" onClick={()=>this.deletePSId(item.shopId)}>删除</a>:null}
									</div>
								</div>
							</li>
						)
					})}
					</ul>
					</Spin>
					</div>

                       <Layer 
							title = ""
							show={this.state.showLayer} 
							hide={this.deletePShideModel.bind(this)}
							width="300px"
							height="150px"
						>
							<div className="row">
								<div className="pop-box-1">																					
									<p>你确定要删除吗？确定后将不能恢复！</p>										
								</div>
										<div className="pop-btn" style={{padding:'7px 0'}}>
											<Button loading={this.state.loading} onClick={()=>this.deleteCourseIdhideModel()} className="btn btn-blue">取消</Button>
											<Button loading={this.state.loading} className="btn btn-blue" onClick={()=>{this.uporPSDelete(this.state.deletePSId,'R')}}>确认</Button>
										</div>
							</div>
			       		</Layer>

					<div className="line"></div>
					<Pages totalPage={this.state.totalPage} jump={this.jump.bind(this)} />
					</div>
			</div>

		)
	}

}
export default PointShopManage

